package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishDto;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.IDishFlavorService;
import com.itheima.reggie.service.IDishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 员工业务层实现
 *
 * @author panda
 * @since 2022/12/25 2:16
 */
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish>
        implements IDishService {



    @Autowired
    private IDishFlavorService dishFlavorService;

    //开启事务管理,因为mabatisPlus不支持多表操作,并且要在启动类上说明
    //@EnableTransactionManagement
    @Transactional
    @Override
    public void saveWithFlavor(DishDto dishDto) {
        //因为在dishDto类中,他继承了dish类,所以可以直接使用MP,直接将dishdto传进去
        this.save(dishDto);
        //2,将菜品信息保存到dishFlavor口味表
        //获取传过来的口味list集合
        List<DishFlavor> flavors = dishDto.getFlavors();
        //进行遍历,再遍历的同时进行将dishId传到每条口味信息当中
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dishDto.getId());
        }
        //以上代码可以使用lambda表达式
       /* flavors.stream().forEach((item)->{
            item.setDishId(dishDto.getId());
        });*/


        //4,最后将全部list集合执行适合的MP命令
        dishFlavorService.saveBatch(flavors);
    }

    @Override
    public DishDto findIdWithFlavor(Long id) {
        //1,先将dish信息存储到dishDto中
        DishDto dishDto = new DishDto();
        Dish dish = this.getById(id);
        BeanUtils.copyProperties(dish,dishDto);
        //2,将菜品口味信息也存储到dishDTO当中
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId, dish.getId());
        List<DishFlavor> dishFlavorsList = dishFlavorService.list(queryWrapper);
        //3,最后将获取到的的口味信息存入dishDto当中
        dishDto.setFlavors(dishFlavorsList);
        return dishDto;
    }

    //由于涉及多表需要添加事务管理
    @Transactional
    @Override
    public void updateWithFlavor(DishDto dishDto) {
        //先修改dish表中的内容
        this.updateById(dishDto);
        //再去修改dishFlavor口味表中的内容
        //应该采用先删除在去添加的方式去实现
        //删除
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(queryWrapper);
        //添加
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors.stream().forEach((item)->item.setDishId(dishDto.getId()));
        dishFlavorService.saveBatch(flavors);
    }
}